package com.ayuku.retail.business.customers;

import java.util.List;

import com.ayuku.commons.AyukuDB;
import com.ayuku.commons.UtilServer;
import com.ayuku.retail.persistence.model.Customer;

public class CustomerImpl {
	public static List<Customer> getList(String arg) throws Exception {
		List<Customer> lst = AyukuDB
				.getPersist()
				.readList(
						Customer.class,
						"SELECT * FROM Customer WHERE code LIKE ucase(?) or name LIKE ucase(?)or email LIKE ucase(?) or telp LIKE ucase(?)",
						new Object[] { arg, arg, arg, arg });
		return lst;
	}

	public static Customer getById(String key) throws Exception {
		Customer obj = (Customer) AyukuDB.getPersist().readByPrimaryKey(
				Customer.class, new Object[] { key });
		return obj;
	}

	public static int add(Customer user) throws Exception {
		setModifiedDate(user);
		return AyukuDB.getPersist().insert(user);
	}

	public static int update(Customer user) throws Exception {
		setModifiedDate(user);
		return AyukuDB.getPersist().update(user);
	}

	public static int delete(String key) throws Exception {
		int n = AyukuDB.getPersist().executeUpdate(
				"delete from Customer where code = ?",
				new Object[] { key.trim() });
		return n;
	}

	public static int delete(List<String> ids) throws Exception  {
		int n = 0;
		try {
			AyukuDB.getPersist().setAutoCommit(false);
			for (int j = 0; j < ids.size(); j++) {
				String key = ids.get(j);
				n += delete(key);
			}
			AyukuDB.getPersist().commit();
		} catch (Exception e) {
			e.printStackTrace();
			AyukuDB.getPersist().rollback();
			throw new Exception();
		} finally {
			AyukuDB.getPersist().setAutoCommit(true);
		}
		return n;
	}

	private static void setModifiedDate(Customer pjo) throws Exception {
		pjo.setModifiedDate(UtilServer.getCurrentDate());
		if (pjo.getCreatedDate() == null) {
			pjo.setCreatedDate(UtilServer.getCurrentDate());
		}
	}

}
